using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace DTFramework.Util
{
    /// <summary>
    /// UI 层级过滤检测
    /// </summary>
    public static class UIRaycastUtil
    {
        private static EventSystem GetEventSystem
        {
            get => (EventSystem.current ??= new GameObject().AddComponent<EventSystem>());
        }
        /// <summary>
        /// 是否在MaskUI上
        /// </summary>
        /// <returns></returns>
        public static bool IsPointerOverMaskUI(GameObject gameObj)
        {
            Vector2 screenPosition = Input.mousePosition;
            //实例化点击事件
            PointerEventData eventDataCurrentPosition = new PointerEventData(GetEventSystem);
            //将点击位置的屏幕坐标赋值给点击事件
            eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y);

            List<RaycastResult> results = new List<RaycastResult>();
            //向点击处发射射线
            GetEventSystem.RaycastAll(eventDataCurrentPosition, results);

            foreach (var result in results)
            {
                if (result.gameObject == gameObj)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 是否在MaskUI上
        /// </summary>
        /// <returns></returns>
        public static bool IsPointerOverMaskUI(string tag)
        {
            Vector2 screenPosition = Input.mousePosition;
            //实例化点击事件
            PointerEventData eventDataCurrentPosition = new PointerEventData(GetEventSystem);
            //将点击位置的屏幕坐标赋值给点击事件
            eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y);

            List<RaycastResult> results = new List<RaycastResult>();
            //向点击处发射射线
            GetEventSystem.RaycastAll(eventDataCurrentPosition, results);

            foreach (var result in results)
            {
                if (result.gameObject.tag == tag)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 是否在MaskUI上
        /// </summary>
        /// <returns></returns>
        public static bool IsPointerOverMaskUI(int layer)
        {
            Vector2 screenPosition = Input.mousePosition;
            //实例化点击事件
            PointerEventData eventDataCurrentPosition = new PointerEventData(GetEventSystem);
            //将点击位置的屏幕坐标赋值给点击事件
            eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y);

            List<RaycastResult> results = new List<RaycastResult>();
            //向点击处发射射线
            GetEventSystem.RaycastAll(eventDataCurrentPosition, results);

            foreach (var result in results)
            {
                if (result.gameObject.layer == layer)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
